package org.example;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Main {
    public static void main(String[] args) {
        LTicket ticket = new LTicket();
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "AA").start();

        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "BB").start();

        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }, "CC").start();
    }
}

class Ticket {
    private int ticketNo = 30;

    public synchronized void sale() {
        if (ticketNo > 0) {
            System.out.println(Thread.currentThread().getName() + ":卖出:" + ticketNo-- + "剩下" + ticketNo);
        } else {
            System.out.println(Thread.currentThread().getName() + ":已经卖完");
        }
    }
}

class LTicket {
    private int ticketNo = 30;
    private final Lock lock = new ReentrantLock();

    public void sale() {
        lock.lock();
        try {
            if (ticketNo > 0) {
                System.out.println(Thread.currentThread().getName() + ":卖出:" + ticketNo-- + "剩下" + ticketNo);
            } else {
                System.out.println(Thread.currentThread().getName() + ":已经卖完");
            }
        } finally {
            lock.unlock();
        }
    }
}